package database

import (
	"crypto/md5"
	"fmt"
	"os"
	"time"

	"github.com/howeyc/gopass"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 定义classmates表里的信息
type Classmates struct {
	Id        int
	Name      string
	Sn        string
	Sex       string
	Classname string
	Pswd      string
	Records   string
	Money     float32
	Birthday  time.Time
	Email     string
	Classid   int
}

var DB *gorm.DB

func DBEmo() {

	for {

		var wdc Classmates
		var findname string
		fmt.Println("请输入你要找的人的名字：")
		fmt.Scanln(&findname)
		DB.Where("name = ?", findname).First(&wdc)
		fmt.Println(wdc.Name)
		fmt.Println(wdc.Sn)
		fmt.Println(wdc.Classname)

		fmt.Println("+++++++++++++")
	}
}

// 连接数据库
func init() {
	dsn := "root:123456@tcp(172.14.1.71:3306)/classmates?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("连接数据库失败，原因是：", err.Error())

		return
	}
	fmt.Println("连接成功!", DB)
	// var wdc Classmates
	// var findname string
	// fmt.Println("请输入你要找的人的名字")
	// fmt.Println(&findname)
	// db.Where("name = ?", findname).First(&wdc)
	// fmt.Println(wdc.Name)
	// fmt.Println(wdc.Classname)
	// fmt.Println("----------------------")
}

// 登录函数

func Login() bool {
	var name string
	fmt.Println("请输入用户名：")
	fmt.Scanln(&name)
	if len(name) < 2 {
		fmt.Println("用户名需要大于2位")
		return false
	}
	var pswd string
	fmt.Println("请输入密码:")
	// true密码显示**，false显示空白
	pawdBytes, err := gopass.GetPasswdPrompt("密码", true, os.Stdin, os.Stdout)
	if err != nil {
		fmt.Println("GetPasswdPrompt 失败", err.Error())
		return false
	}
	// 加密字母大写用大写X，小写字母用小写x
	pswd = string(pawdBytes)
	pswd = fmt.Sprintf("%x", md5.Sum([]byte(pswd)))
	// fmt.Scanln(&pswd)
	var user Classmates
	// 用gorm实现
	// db.Where("name = ?", name).First(&user)

	DB.Raw("SELECT * FROM classmates.classmates where name = ?", name).Scan(&user)
	// 验证错误
	// fmt.Println(user.Pswd, "=====", pswd)
	if user.Pswd == pswd {
		fmt.Println("登录成功,欢迎您！", user.Name)
		AutoWeriteLog(LoginUser.Name, LoginUser.Id, time.Now(), "登录了系统", LoginUser.Sn)
		return true

	} else {
		AutoWeriteLog(LoginUser.Name, 0, time.Now(), "尝试登录,没有成功", LoginUser.Sn)
		return false
	}

}

var LoginUser Classmates

// 修改密码
func ResetPswd() {
	// 1.先验证当前登录者的密码
	var oldPswd string
	fmt.Println("请输入当前密码验证")
	fmt.Scanln(&oldPswd)
	oldPswd = fmt.Sprintf("%x", md5.Sum([]byte(oldPswd)))

	if LoginUser.Pswd != oldPswd {
		fmt.Println("你输入的密码有误")
		return
	}
	// 2.让用户输入新密码
	var newPswd string
	fmt.Println("请输入新密码")
	fmt.Scanln(&newPswd)
	// 3.用户在输入新密码
	var newPswdAgain string
	fmt.Println("请输入当前密码再次验证")
	fmt.Scanln(&newPswdAgain)
	if newPswd != newPswdAgain {
		fmt.Println("你输入2次密码有误,请重试")
		return
	}
	// 4.将密码存入数据
	LoginUser.Pswd = fmt.Sprintf("%x", md5.Sum([]byte(newPswd)))
	DB.Save(&LoginUser)
	fmt.Println("修改密码成功")

	AutoWeriteLog(LoginUser.Name, LoginUser.Id, time.Now(), "成功修改了密码", LoginUser.Sn)

}

// 修改当前登录人的个人资料
func ModifyMyInfo() {
	fmt.Println("你当前名字是:", LoginUser.Name, "请输入新的名字")
	fmt.Scanln(&LoginUser.Name)
	if len(LoginUser.Name) < 3 {
		fmt.Println("用户名不能太短")
		return
	}
	var newName string
	fmt.Scanln(&newName)
	fmt.Println("你当前性别是:", LoginUser.Sex, "请输入新的性别")
	fmt.Scanln(&LoginUser.Sex)
	if LoginUser.Sex != "男" && LoginUser.Sex != "女" {
		fmt.Println("性别只分男和女")
		return
	}
	fmt.Println("你当前学号是:", LoginUser.Sn, "请输入新的学号")
	var newSn string
	fmt.Scanln(&newSn)
	DB.Save(&LoginUser)
	fmt.Println("修改完成")
	AutoWeriteLog(LoginUser.Name, LoginUser.Id, time.Now(), "修改了自己的资料", LoginUser.Sn)
}

// 定义records表里的信息
type Records struct {
	Id         int
	Name       string
	Sn         string
	Tel        string
	Comments   string
	Classid    int
	Createtime time.Time
	Classromr  string
}

// 加分函数
func Jiafen() {
	var name string
	fmt.Println("请输入要修改考勤的人姓名")
	fmt.Scanln(&name)
	var beoperSN string
	var recordsList []Records
	DB.Raw("SELECT * from classmates.records where name =?", name).Scan(&recordsList)
	for _, record := range recordsList {
		fmt.Printf("id:%5d   |    姓名:%10s |  分数:%20v  | 时间:%20v   \n", record.Id, record.Name, record.Comments, record.Createtime)
		beoperSN = record.Sn
	}

	fmt.Println("请输入考勤id")
	var records int
	fmt.Scanln(&records)
	fmt.Println("请输入要加的分数")
	var fenshu string
	fmt.Scanln(&fenshu)
	DB.Exec("update classmates.records set comments =? where id =?", fenshu, records)
	fmt.Println("加分成功")
	DB.Raw("SELECT * from classmates.records where name =? ", name).Scan(&recordsList)
	for _, record := range recordsList {
		fmt.Printf("id:%5d   |    姓名:%10s |  分数:%20v  | 时间:%20v   \n", record.Id, record.Name, record.Comments, record.Createtime)
	}

	AutoWeriteLog(LoginUser.Name, LoginUser.Id, time.Now(), "给"+name+"加了"+fenshu, beoperSN)

}

type logs struct {
	Id          int
	OpName      string
	OpId        int
	Createtime  time.Time
	Content     string
	BeOperateSn string
}

func AutoWeriteLog(operName string, operID int, shijian time.Time, content string, beOpSN string) {
	var thisLog logs
	thisLog.BeOperateSn = beOpSN
	thisLog.Content = content
	thisLog.OpName = operName
	thisLog.OpId = operID
	thisLog.Createtime = shijian
	DB.Save(&thisLog)

}

// 添加新同学
func AddStudent() {
	//数据库方法
	// database.DB.Exec("insert into classmates.classmates values ('')")
	var newstudent Classmates
	fmt.Println("请输入新同学的名字")
	fmt.Scanln(newstudent.Name)
	fmt.Println("请输入新同学的性别")
	fmt.Scanln(newstudent.Sex)
	fmt.Println("请输入新同学的学号")
	fmt.Scanln(newstudent.Sn)
	DB.Save(&newstudent)
	fmt.Println("添加完成")

}

// 转账
func Zhuanzhang() {
	var targetName string
	fmt.Println("请输入你要转账的人的名字")
	fmt.Scanln(&targetName)

	var targetList []*Classmates
	DB.Raw("SELECT * from classmates.classmates where name =? ", targetList).Scan(&targetList)
	fmt.Println("找到了下面同名的人员，请根据学号进行确认")
	for _, person := range targetList {
		fmt.Println("sn", person.Sn, "name", person.Name, "ID:", person.Id)

	}

	var targetID int
	var edu float32
	fmt.Println("请输入对方id")
	fmt.Scanln(&targetID)
	fmt.Println("请输入要转账的额度")
	fmt.Scanln(&edu)

	LoginUser.Money = edu

	DB.Save(LoginUser)
	DB.Exec("UPDATE classmates.classmates set money =(money+ ? ) where id = ?", edu, targetID)
	fmt.Println("转账完成")

}
